package com.lenovo.spider.domain;

import cn.hutool.core.collection.CollUtil;
import lombok.Getter;
import lombok.ToString;
import lombok.val;

import java.io.Serializable;
import java.util.List;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/21 14:47
 */
@Getter
@ToString(of = {"success", "request", "response"})
public class Task implements Serializable {
    /**
     * 任务是否成功
     */
    private boolean success;
    /**
     * 任务失败的异常原因
     */
    private Throwable cause;
    /**
     * 任务请求
     */
    private Request request;
    /**
     * 请求响应
     */
    private Response response;
    /**
     * 新页面的链接
     */
    private List<Request> nextRequests;
    /**
     * 页面中提取的数据
     */
    private ResultItem item;
    /**
     * 站点配置
     */
    private SiteConfig siteConfig;

    /**
     * 根据请求创建任务
     *
     * @param request
     * @return
     */
    public static Task create(Request request) {
        val task = new Task();
        task.success = true;
        task.request = request;
        return task;
    }

    /**
     * 设置任务失败
     *
     * @param cause
     * @return
     */
    public Task error(Throwable cause) {
        this.success = false;
        this.cause = cause;
        return this;
    }

    /**
     * 设置下载响应
     *
     * @param response
     * @return
     */
    public Task setResponse(Response response) {
        this.response = response;
        return this;
    }

    /**
     * 设置解析数据
     *
     * @param resultItem
     * @return
     */
    public Task setItem(ResultItem resultItem) {
        this.item = resultItem;
        return this;
    }

    /**
     * 设置新抓取的页面
     *
     * @param requests
     * @return
     */
    public Task addNextRequest(Request... requests) {
        if (this.nextRequests == null) {
            this.nextRequests = CollUtil.newArrayList();
        }
        CollUtil.addAll(this.nextRequests, requests);
        return this;
    }

    public String getCurUrl() {
        return response != null ? response.getRelUrl() : request.getUrl();
    }
}
